package dev.wanheng.springjwtlogin.controller;

import dev.wanheng.springjwtlogin.dto.LoginResponseDto;
import dev.wanheng.springjwtlogin.dto.PlainResult;
import dev.wanheng.springjwtlogin.dto.UserDto;
import dev.wanheng.springjwtlogin.service.UserService;
import dev.wanheng.springjwtlogin.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;

@RestController

@RequestMapping("/auth")
@CrossOrigin(origins = "*", maxAge = 3000)
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @PostMapping("/register")
    public PlainResult<Void> register(@RequestBody UserDto userDto) {

        UserDto user = userService.getUserByUsername(userDto.getUsername());
        if (user != null) {
            return PlainResult.fail(400, "用户名已存在");
        }

        if (userDto.getPhone() == null || userDto.getPhone().isEmpty()) {
            return PlainResult.fail(401, "手机号不能为空");
        }

        UserDto userPhone = userService.getUserByPhone(userDto.getPhone());
        if(userPhone != null) {
            return PlainResult.fail(406, "电话号码已经被其他用户使用，请更换电话号码");
        }

        userService.register(userDto);
        return PlainResult.success(null);
    }

    @PostMapping("/login")
    public PlainResult<LoginResponseDto> login(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserDto user = userService.getUserByUsername(userDto.getUsername());
        userDto.setIp(getClientIp(request));
        System.out.println(userDto.getIp());
        if (user == null) {
            return PlainResult.fail(403, "用户名不存在");
        }
        else{
            if(!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
                return PlainResult.fail(405, "密码不正确");
            }
        }
        Authentication authenticate = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken
                        (userDto.getUsername(), userDto.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        if (userDto.getIp() != null && !userDto.getIp().isEmpty()) {
            userService.updateUserIp(userDto.getUsername(), userDto.getIp());
        }

        LoginResponseDto loginResponseDto = new LoginResponseDto();
        loginResponseDto.setToken(jwtUtil.generateToken(userDto.getUsername(), userDto.getPhone()));
        return PlainResult.success(loginResponseDto);
    }

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // X-Forwarded-For 可能是：client, proxy1, proxy2
            // 取第一个非 unknown 的值
            String[] parts = ip.split(",");
            for (String part : parts) {
                part = part.trim();
                if (part.length() != 0 && !"unknown".equalsIgnoreCase(part)) {
                    return part;
                }
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        // 最后退回到远端地址
        return request.getRemoteAddr();
    }
}


